/* eslint-disable no-shadow */
/* eslint-disable no-unused-vars */
import React, { memo, useState, useEffect, useCallback, useRef } from "react";
import Taro, {
  useRouter,
  usePageScroll,
  useReachBottom,
  useDidShow,
} from "@tarojs/taro";
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import { updateState } from "@/store/actions/global";
import { View } from "@tarojs/components";
import { Loading, Empty, Tabs, Tab, Icon, ActionSheet } from "@antmjs/vantui";
import debounce from "lodash/debounce";
import axios from "@/axios";
import { getUserRecipe, userOpRecipe, delRecipe } from "@/axios/api/recipe";
import Authorization from "@/components/Authorization";
import RecipeItem from "@/components/RecipeItem";
import BackTop from "@/components/BackTop";
import Navbar from "@/components/Navbar";
import { themeColor } from "../../utils/config";
import "./index.less";

const Index = () => {
  const router = useRouter();
  const dispatch = useDispatch();
  const { globalData } = useSelector(
    (state) => ({ globalData: state.globalData }),
    shallowEqual
  );
  const { isLogin, showBackTop, systemInfo, navbarHeight, userInfo } = globalData;
  const { type = 0, user_id = userInfo && userInfo.user_id, username = userInfo && userInfo.username } = router.params;
  const { screenHeight } = systemInfo;
  const [active, setActive] = useState(Number(type));
  const [isLoading, setLoading] = useState(false);
  const [currentSelect, setCurrentSelect] = useState({});
  const [ListData, setListData] = useState([]);
  const [isMore, setIsMore] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const [navbarTitle] = useState(username);
  const [flag, setFlag] = useState(false);
  const optionsData = [
    [
      {
        name: "编辑",
      },
      {
        name: "删除",
        color: "#ee0a24",
      },
      {
        name: "取消",
        color: "#646566",
      },
    ], [
      {
        name: "取消收藏",
        color: "#ee0a24",
      },
      {
        name: "取消",
        color: "#646566",
      },
    ]
  ];
  const [options, setOptions] = useState(optionsData[0]);
  const [showOptionBar, setShowOptionBar] = useState(false);
  const isOwner = !router.params.user_id || router.params.user_id == userInfo.user_id;
  const [tab] = useState([
    {
      id: 1,
      value: isOwner ? '我的菜谱' : 'Ta的菜谱'
    },
    {
      id: 2,
      value: isOwner ? '我的收藏' : 'Ta的收藏'
    }
  ])
  const onChange = ({ detail: { index } }) => {
    if (flag) {
      setListData([]);
      getData(index + 1, 1);
      setActive(index);
      setOptions(optionsData[index])
    }
  };
  const handleClick = useCallback(
    debounce(
      (type, id, username) => {
        console.log("CLICK", type, id, username);
        let url = "";
        if (type === "recipe") {
          url = "/pages/recipeInfo/index?recipe_id=" + id;
        }
        if (type === "user") {
          url = `/pages/userCenter/index?user_id=${id}&username=${username}`;
        }
        if (!isLogin) {
          dispatch(
            updateState({
              isShowGrant: true,
            })
          );
        } else {
          jumpTo(url);
        }
      },
      500,
      {
        leading: true,
        trailing: false,
      }
    ),
    [isLogin]
  );
  const jumpTo = (url) => {
    Taro.navigateTo({
      url,
    });
  };
  const getData = (type = 1, page = 1) => {
    setLoading(true);
    axios.post(getUserRecipe, { type, page, user_id }).then((res) => {
      const { data, code } = res;
      if (code === 200) {
        // const { list, pageNum, pageSize, total } = data;
        console.log(data, res.msg);
        const { pageNum, isMore, list } = data;
        if (page === 1) {
          setListData(list);
          setIsMore(isMore)
          setPageNum(pageNum)
        } else {
          setListData((pre) => [...pre, ...list]);
          setIsMore(isMore)
          setPageNum(pageNum)
        }
      }
      setLoading(false);
    });
  };
  const onClose = () => {
    setShowOptionBar(false);
    setCurrentSelect({});
  };
  const onSelect = ({ detail }) => {
    console.log(detail, currentSelect);
    const { name } = detail;
    const { index, recipe_id, title } = currentSelect;
    if (name === '删除') {
      Taro.showModal({
        title: '提示',
        content: `你确定要删除菜谱「${title}」吗`,
        success: function (res) {
          if (res.confirm) {
            axios.post(userOpRecipe, { recipe_id, user_id, type: 4 }).then(res => {
              if (res.code === 200) {
                setListData(pre => {
                  pre.splice(index, 1);
                  return [...pre]
                })
              }
            })
          }
        }
      })
    } else if (name === '编辑') {
      Taro.navigateTo({ url: `/pages/recipeAdd/index?recipe_id=${recipe_id}&type=1` })
    } else if (name === '取消收藏') {
      axios.post(userOpRecipe, { recipe_id, user_id, type: 2 }).then(res => {
        if (res.code === 200) {
          setListData(pre => {
            pre.splice(index, 1);
            return [...pre]
          })
        }
      })
    }
  };
  const getListDom = (type = 1) => {
    return ListData.map((item, index) => {
      const { recipe_id, title } = item;
      return (
        <View className='relative'>
          <RecipeItem
            key={recipe_id}
            data={item}
            handleClick={handleClick}
          ></RecipeItem>
          {isOwner && <View className='icon-select' onClick={() => {
            setCurrentSelect({
              index,
              recipe_id,
              title
            })
            setShowOptionBar(true)
          }}>
            <Icon name="ellipsis" size='50'></Icon>
          </View>}
        </View>
      );
    });
  };
  useEffect(() => {
    if (!isLogin) {
      dispatch(
        updateState({
          isShowGrant: true,
        })
      );
      return;
    }
    setFlag(true);
    getData(active + 1);
    setOptions(optionsData[active])
  }, [isLogin, dispatch]);
  useDidShow(() => {
    if (flag) {
      getData(active + 1);
    }
  })
  usePageScroll((res) => {
    const flag = res.scrollTop > screenHeight * 1.5;
    if (flag !== showBackTop) {
      dispatch(
        updateState({
          showBackTop: flag,
        })
      );
    }
  });
  useReachBottom(() => {
    if (isMore) {
      getData(active + 1, pageNum + 1);
    }
  });
  return (
    <View className='user-center'>
      <Navbar title={navbarTitle} arrow='true'></Navbar>
      <View className='tab' style={{ top: navbarHeight }}>
        <Tabs active={active} onChange={onChange}>
          {tab.map(item => {
            return <Tab key={item.id} title={item.value}></Tab>
          })}
        </Tabs>
      </View>
      <View className='block'></View>
      <View className='list'>
        {!ListData.length && !isLoading ? <Empty description='暂无菜谱' /> : (getListDom())}
      </View>
      {isLoading ? (
        <View className='loading'>
          <Loading color={themeColor} size='28px' />
        </View>
      ) : null}
      <View className='optionBar'>
        <ActionSheet
          show={showOptionBar}
          actions={options}
          onClose={onClose}
          onSelect={onSelect}
        />
      </View>
      <Authorization canClose={false}></Authorization>
      <View>{showBackTop ? <BackTop top={.75 * screenHeight} /> : null}</View>
    </View>
  );
};

export default memo(Index);
